package cc.laop.business.system;

import cc.laop.business.BaseBusinessImpl;
import cc.laop.dao.system.RoleMapper;
import cc.laop.entity.system.Role;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RoleBusiness extends BaseBusinessImpl<RoleMapper, Role> {

    public List<Role> selectByUser(int userid) {
        return mapper.selectByUser(userid);
    }

    public int insertOrUpdate(Role role, String resids) {
        int result = 0;
        if (role != null) {
            if (role.getId() == 0) {
                List<Role> rl = super.select(role);
                if (rl != null && rl.size() > 0) {
                    return 2;
                }
                result = super.insert(role);
            } else {
                result = super.update(role);
            }
            updatePermission(role.getId(), resids);
        }
        return result;
    }

    public void delete(String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            String[] id = ids.split(",");
            super.delete(id);
        }
    }

    private void updatePermission(int roleid, String resids) {
        if (roleid > 0) {
            mapper.deleteRoleResource(roleid);
            if (StringUtils.isNotEmpty(resids)) {
                String[] resid = resids.split(",");
                for (String i : resid) {
                    if (StringUtils.isNumeric(i)) {
                        Map<String, Integer> map = new HashMap<String, Integer>();
                        map.put("roleid", roleid);
                        map.put("resourceid", Integer.parseInt(i));
                        mapper.insertRoleResource(map);
                    }
                }
            }

        }

    }

}
